Vuex
Vue 的官方状态管理库已更改为 Pinia。Vuex 是 Vue.js 应用程序的状态管理模式 + 库。
pnpm add vuex
使用
import { createStore } from "vuex";
// Create a new store instance.
const store = createStore({
state() {
return {
count: 0,
};
},
mutations: {
increment(state) {
state.count++;
},
},
});
export default store;
应用
main.ts
const app = createApp({ /* your root component */ })
// Install the store instance as a plugin
app.use(store)
API
- State(状态):存储应用的状态数据。
- Getters(获取器):用于从 state 中派生出状态,类似于计算属性。
- Mutations(变更):用于同步地更改 state 的方法。
- Actions(动作):用于提交 mutations,可以包含任意异步操作。
- Modules(模块):将 store 分割成模块,每个模块拥有自己的 state、getters、mutations、actions。